const router = require('koa-router')();

const User = require('../model/user');
const Article = require('../model/article');
const ArticleType = require("../model/articleType")
/**
 * 用户信息
 */
router.post('/user', async (context, next) => {
    let body = context.request.body

    context.verifyParams({
        token:{
            type: 'string',
            required: true
        }
    })
    const type = await ArticleType.find();
    let typeObj = {};
    type.forEach(element => {
        const {_id, type} = element;
        typeObj[_id] = type;
    });
    const users = await User.find({token: body.token})
    if(users.length > 0){
        const id = users[0]._id
        let articleLists = await Article.find({authID:id});
        articleLists = articleLists.map( item => {
            const {_id, title, createdAt, typeID} = item;
            return {id:_id, title, createdAt, typeID, typeName: typeObj[typeID]}
        })

        let resBody = {
            nickName: users[0].nickName,
            articleLists
        }
        context.body = resBody
    }else {
        context.throw(401, "登录失效")
    }

})


module.exports = router